import base64

import requests
import json

API_KEY = "lRJ4IIUodHD1jCkEqLgYPm3K"
SECRET_KEY = "40ACyo2vDygvFP24K2cprdOsWo0nbzri"


class Face:
    def main(self, img1, img2):

        url = "https://aip.baidubce.com/rest/2.0/face/v3/match?access_token=" + self.get_access_token()

        payload = json.dumps([
            {
                "image": img1,
                "image_type": "BASE64"
            },
            {
                "image": img2,
                "image_type": "BASE64"
            }
        ], ensure_ascii=False)
        headers = {
            'Content-Type': 'application/json'
        }

        response = requests.request("POST", url, headers=headers, data=payload.encode("utf-8"))

        return response.json()

    def get_access_token(self):
        """
        使用 AK，SK 生成鉴权签名（Access Token）
        :return: access_token，或是None(如果错误)
        """
        url = "https://aip.baidubce.com/oauth/2.0/token"
        params = {"grant_type": "client_credentials", "client_id": API_KEY, "client_secret": SECRET_KEY}
        return str(requests.post(url, params=params).json().get("access_token"))


face = Face()
